<?php

if (!defined('CORE_PATH'))  die('Access Denied');

class UserManager extends Manager {

    protected $publishField = "Activated";
    protected $models = array("User","Role");

    public function __construct() {
        parent::__construct("users","user_roles");
        $this->setItemClassName('User');
        $this->setCategoryClassName('Role');
        $this->categoryField = "Role";
    }

    /**
     * Returns a User object based on the specified parameters
     * @param mixed $id
     * @return User
     */
    public function getUser($id) {
        return $this->getItem($id);
    }

    /**
     *
     * @param mixed $options
     * @return User[]
     */
    public function getUsers($options) {
        return $this->getItems(0, NULL, $options);
    }

    /**
     * Returns a User Role object
     * @param mixed $id
     * @return Role
     */
    public function getUserRole($id = NULL) {
		return $this->Role->findFirst(array(
			'filter' => array(
				'OR' => array(
					'id' => $id,
					'role_tag' => $id
				)
			)
		));
    }
	
	public function getRoles() {
		return $this->getCategories();	
	}

    /**
     * Updates a User from the CMS interface
     * 
     * @return User 
     */
    public function updateUser() {
        if (!defined("IN_CMS") && !IN_CMS) {
            return;
        }
		
		$role = new Role($_POST['Role']);

        $user = new User(array(
			'id' => $_POST['id'],
			'FirstName' => $_POST['FirstName'],
			'LastName' => $_POST['LastName'],
			'FullName' => $_POST['FirstName'] . ' ' . $_POST['LastName'],
			'Email' => $_POST['Email'],
			'Username' => $_POST['Username'],
			'Level' => $role->getData('role_tag'),
			'Role' => $role->getId()
		));

        $user->save();

        return $user;
    }

    /**
     * Adds a new User from the CMS interface
     * 
     * @return User 
     */
    public function addUser() {
        if (!defined("IN_CMS") && !IN_CMS) {
            return;
        }

        $salt = rand(1, 100000);
        $passhash = md5($_POST['Password'] . $salt);
		
		$role = new Role($_POST['Role']);

        $user = new User(array(
			'FirstName' => $_POST['FirstName'],
			'LastName' => $_POST['LastName'],
			'FullName' => $_POST['FirstName'] . ' ' . $_POST['LastName'],
			'Email' => $_POST['Email'],
			'Username' => $_POST['Username'],
			'Password' => $passhash,
			'PassSalt' => $salt,
			'Level' => $role->getData('role_tag'),
			'Role' => $role->getId()
		));

        $user->save();

        if( $user->getData('Level') == "specific") {
            // get the selected sites
            $sites = $_POST['sites'];
            $date = date("Y-m-d");

            $user_id = $user->getId();

            // for each selected site, insert a record into in the user_sites table
            foreach ($sites as $site) {
                $query = sprintf("INSERT INTO users_sites (User, Site, DateModified) VALUES(%s,%s,%s)", $db->sanitizeInput($user_id, 'int'), $db->sanitizeInput($site, 'int'), $db->sanitizeInput($date, 'text'));

                $db = $this->getDatabase();
                $db->query($query, true);
            }
        }

        return $user;
    }

    public function changeUserPassword() {
        if (!defined("IN_CMS") && !IN_CMS) {
            return;
        }
        
        $old = $_POST['old'];
        $new = $_POST['new'];
        $user = $_POST['user'];

        $user = new User($user);
        $oldPassHash = $user->getPassword();
        $oldPassSalt = $user->getData('PassSalt');
        
        if( $oldPassHash == NULL ) {
            trigger_error("User Specified Is Not Present In The Database");
            return false;
        }
        
        $confirmOldHash = md5($old . $oldSalt);

        // confirm that the supplied password is a valid
        if ($confirmOldHash != $oldPassHash) {
            trigger_error("The Old Password Supplied Is Not Valid. Please Check and Correct");
            return false;
        }

        $newSalt = rand(1, 100000);
        $newPassHash = md5($new . $newSalt);

        $user->setData('Password', $newPassHash);
        $user->setData('PassSalt', $newSalt);
        $user->save();
        
        
        return true;
    }
    
    /**
     * Returns a user from the database based on the Username supplied
     * @param string $username
     * @return User
     */
    public function getUserByUsername($username) {
        
        if( !defined("IN_CMS") || !IN_CMS ) {
            return NULL;
        }
        
        return $this->User->findFirst( array(
           'filter' => array(
               'OR' => array(
                   'Username' => $username,
                   'Email' => $username
               )
           )
        ));
    }

}




?>
